<template>
  <div class="app-container">
      <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button class="btn-add" @click="handleAddUser()" size="mini">
        添加新用户
      </el-button>
    </el-card>
    <el-table ref="productTable"
                :data="list"
                style="width: 100%"
                v-loading="listLoading"
                border>
        <!-- <el-table-column type="selection" width="60" align="center"></el-table-column> -->
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="头像" width="120" align="center">
          <template slot-scope="scope"><img style="height: 80px" :src="scope.row.icon"></template>
        </el-table-column>
        <el-table-column label="昵称" width="100" align="center">
          <template slot-scope="scope">{{scope.row.nickName}}</template>
        </el-table-column>
         <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">{{scope.row.status ==1 ?'正常':'有问题'}}</template>
        </el-table-column>
         <el-table-column label="创建时间" width="170" align="center">
          <template slot-scope="scope">{{scope.row.createTime}}</template>
        </el-table-column>
        <el-table-column label="邮箱" width="150" align="center">
          <template slot-scope="scope">{{scope.row.email}}</template>
        </el-table-column>
        <el-table-column label="备注" width="100" align="center">
          <template slot-scope="scope">{{scope.row.note}}</template>
        </el-table-column>
        <el-table-column label="操作" width="360" align="center">
          <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleEditUser(scope.$index, scope.row)">编辑
              </el-button>
              <el-button
                size="mini"
                @click="handleUpdateRole(scope.$index, scope.row)">角色分配
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDeleteUser(scope.$index, scope.row)">删除
              </el-button>
          </template>
        </el-table-column>
    </el-table>
    <!-- 新增用户的弹窗 -->
    <el-dialog title="新增用户" :visible.sync="isNewUserOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form :model="newForm" style="width:25rem;" :rules="newFormRules" >
            <el-form-item label="用户名" prop="username" required label-width="5rem">
                <el-input v-model="newForm.username" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="nickName" required label-width="5rem">
                <el-input v-model="newForm.nickName" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" label-width="5rem">
                <el-input v-model="newForm.password" type="password" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" label-width="5rem">
                <el-input v-model="newForm.email" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <p style="margin-left:30px;">选择喜欢的头像</p>
            <el-radio-group v-model="newForm.iconIndex" class="portrait">
              <el-radio :label="item.index" v-for="(item) in portraitObj" :key="item.index">
                <el-image style="width: 66px; height: 66px" :src="item.src" ></el-image>
              </el-radio>
            </el-radio-group>
            <el-form-item label="备注"  label-width="5rem">
                <el-input v-model="newForm.note" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveNewUser('newForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isNewUserOpen = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 编辑用户的弹窗 -->
    <el-dialog title="编辑用户" :visible.sync="isEditUserOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form :model="editForm" style="width:25rem;" :rules="editFormRules" >
            <el-form-item label="用户名" prop="username" required label-width="5rem">
                <el-input v-model="editForm.username" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="nickName" required label-width="5rem">
                <el-input v-model="editForm.nickName" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" label-width="5rem">
                <el-input v-model="editForm.password" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <p style="margin-left:30px;">修改您的头像</p>
            <el-radio-group v-model="editForm.iconIndex" class="portrait">
              <el-radio :label="item.index" v-for="(item) in portraitObj" :key="item.index">
                <el-image style="width: 66px; height: 66px" :src="item.src" ></el-image>
              </el-radio>
            </el-radio-group>
            <el-form-item label="备注" prop="note" label-width="5rem">
                <el-input v-model="editForm.note" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveUserInfo('editForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isEditUserOpen = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 编辑用户角色的弹窗 -->
    <el-dialog title="编辑用户角色" :visible.sync="isRoleOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <!-- <div :model="editRoleForm" style="width:25rem;" :rules="editRoleFormRules" > -->
        <div style="width:25rem;" >
          <el-checkbox-group v-model="selectedRole" @change="roleChange">
            <el-checkbox v-for="role in allRoleList" :label="role.id" :key="role.id">{{role.name}}</el-checkbox>
          </el-checkbox-group>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveUserRoleInfo" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isRoleOpen = false">关闭</el-button>
        </div>
    </el-dialog>
  </div>
</template>
<script>
    import {
    fetchUserList,
    updateUserInfo,
    newUserInfo,
    deleteUser,
    getCurUserRole,
    updateUserRoleInfo,
  } from '@/api/user'
   import {fetchRoleList} from '@/api/role'
//   import {fetchList as fetchProductAttrList} from '@/api/productAttr'
//   import {fetchList as fetchBrandList} from '@/api/brand'
//   import {fetchListWithChildren} from '@/api/productCate'

  const defaultListQuery = {
    keyword: null,
    pageNum: 1,
    pageSize: 5,
    publishStatus: null,
    verifyStatus: null,
    productSn: null,
    productCategoryId: null,
    brandId: null
  };
  export default {
    name: "UserList",
    data() {
      return {
          list:[],
          listQuery:Object.assign({}, defaultListQuery),
          portraitObj:[
            {index:1, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/4f765a4489364859abf49cdb05ae76db.jpg'},
            {index:2, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/4e2c708f7d424cea9ae0792b05172ce0.jpg'},
            {index:3, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/99399693fde649b29e45aeb57d40e0ff.jpg'},
            {index:4, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/e1a7e1bbccd742788bddd7ad45341a46.jpg'},
            {index:5, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/4bd92ec307324ac397c767e5b251872d.jpg'},
            {index:6, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/0379caa661fd4cc1afa735f2893892af.jpg'},
            {index:7, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/5e7de88961b74b85b66386fa9f9fb2c3.jpg'},
            {index:8, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/da65ba447c3049a282199a5fee83a322.jpg'},
            {index:9, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/0b846619ced24e118d5b2916c29add3e.jpg'},
            {index:10, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/c9eb2d1ca9e9434da5b537c048294778.jpg'},
            {index:11, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/56354c745c6646e5a6bc85227b52e02c.jpg'},
            {index:12, src:'https://ys-mall-test-1300674810.cos.ap-chengdu.myqcloud.com/img_folder/ad6a77147e2f4f76860ad0fde5920756.jpg'},
          ],
          newForm:{//新增用户弹框里内容
            username:'',
            nickName:'',
            password:'',
            note:'',
            email:'',
            iconIndex:1,//用户头像index
            icon: "",//用户头像
          },
          editForm: {//编辑用户弹框里内容
            currentUId:0,
            id:0,
            username:'',
            nickName:'',
            password:'',
            note:'',
            iconIndex:1,
            icon:"",
          },
          newFormRules:{
            username:[
                { required: true,  message: '用户名不能为空', trigger: ['blur','change']}
             ],
             nickName:[
                { required: true,  message: '昵称不能为空', trigger: ['blur','change']}
             ],
             password:[
                { required: true,  message: '密码不能为空', trigger: ['blur','change']},
                {min:6, max:20, message:"密码长度不能大于20", trigger:['blur','change']}
             ],
             
          },
          editFormRules:{
            username:[
                { required: true,  message: '用户名不能为空', trigger: ['blur','change']}
             ],
             nickName:[
                { required: true,  message: '昵称不能为空', trigger: ['blur','change']}
             ],
          },
          currentOpeId:0,//编辑角色的当前用户id
          allRoleList:[],//所有的角色列表
          userRoleId:[],//当前用户的role id
          selectedRole:[],//用户弹窗里选择的选择的role id
          isNewUserOpen:false,//新增用户弹窗
          isEditUserOpen:false,//编辑用户弹窗
          isRoleOpen:false,//编辑角色弹窗
      }
    },
    computed:{
      //fileList
    },
    created() {
      this.getList();
      this.getRoleList();
    },
    methods:{
      getList() {
        this.listLoading = true;
        //console.log(this.listQuery);
        let params={
            //name:"name",
            pageNum:1,
            pageSize:20
        }
        fetchUserList(params).then(response => {
            this.listLoading = false;
            this.list = response.data.list;
            //this.total = response.data.total;
            console.log(this.list);
        });
      },
      handleEditUser(index,item){
        this.isEditUserOpen = true;
        this.editForm.currentUId = item.id;
        this.editForm.id = item.id;
        this.editForm.username = item.username;
        this.editForm.nickName = item.nickName;
        this.editForm.password = '';
        let aimIndex =0;
        Object.keys(this.portraitObj).forEach((idx)=>{
          console.log(idx,this.portraitObj[idx]);
          //console.log(typeof idx)
          if(this.portraitObj[idx].src == item.icon){
            aimIndex = parseInt(idx) + 1
          }
        });
        console.log(aimIndex);
        this.editForm.iconIndex = aimIndex;
        this.editForm.note = item.note;
      },

      handleAddUser(){
          this.isNewUserOpen = true;
      },
      
      saveNewUser(){
        console.log(this.newForm);
        let index = this.newForm.iconIndex;
        this.newForm.icon = this.portraitObj[index-1].src;
        console.log(this.newForm);
        newUserInfo(this.newForm).then(response=>{
            if(response.code == 200){
                this.$message({
                  message: '新建成功',
                  type: 'success',
                  duration: 1000
              });
            this.isNewUserOpen=false;
            this.getList();
            }
        })
      },
      saveUserInfo(){
          //console.log(this.editForm);
          let passTemp= this.editForm.password;
          if (!passTemp){
            delete this.editForm.password
          }
            let index = this.editForm.iconIndex;
        this.editForm.icon = this.portraitObj[index-1].src;
          //console.log(this.editForm);
        updateUserInfo(this.editForm.currentUId,this.editForm).then(response=>{
            this.$message({
                message: '修改成功',
                type: 'success',
                duration: 1000
            });
            this.isEditUserOpen=false;
            this.getList();
        });
      },
      handleUpdateRole(index,item){
        console.log(item.id);
        this.currentOpeId = item.id;
        this.getCurUserRole();
      },
      getRoleList() {
        let self = this;
        fetchRoleList().then(response => {
            if(response.code === 200){
              self.allRoleList = response.data;
            }
        });
      },
      getCurUserRole(){
        let self = this;
        let id = self.currentOpeId;
        getCurUserRole(id).then(res =>{
          let roleInfo = res.data;
          let roleIds =[];
          roleInfo.forEach(item=>{
            roleIds.push(item.id);
          })
          self.userRoleId = roleIds; //当前用户的role id
          self.selectedRole = JSON.parse(JSON.stringify(roleIds));
          self.isRoleOpen =true;
        })
      },
      roleChange(){
        console.log(this.selectedRole)
      },
      saveUserRoleInfo(){
        let self = this;
        if (!self.selectedRole || self.selectedRole.length ==0){
          this.$message({
            message: '请选择合适的角色',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        let params = new URLSearchParams();
        params.append('adminId', self.currentOpeId);
        params.append('roleIds', self.selectedRole);
        updateUserRoleInfo(params).then(res=>{
          if(res.code === 200){
            this.$message({
              message: '角色修改成功',
              type: 'success',
              duration: 1000
            });
            self.isRoleOpen = false;
            self.getList();
          }
        })
      },
      handleDeleteUser(index,item){
          let self = this;
           self.$confirm('删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                console.log(11);
                deleteUser(item.id).then(response=>{
                    console.log(22)
                    if(response.code === 200){
                        self.$message({
                            message: '删除成功',
                            type: 'success',
                            duration: 1000
                        });
                        self.getList();
                    }
                });
            }).catch(() => {
                // self.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });          
            });
      },
      
    }
  }
</script>
<style scoped>
.btn-add{
    font-size: 14px;
    padding: 10px;
    margin-top: -8px;
  color:#fff;
  background-color:#417FF6;
}
/* 弹出框的宽度 */
.adjustmentBox >>> .el-dialog{
  width: 28rem;
} 


.portrait{
  margin-left: 30px;
  margin-bottom: 20px;
}
.portrait >>> .el-radio{
  display: inline-flex;
  align-items: center;
  margin-top: 10px;
}
</style>